import { EditOutlined } from '@ant-design/icons'
import { Avatar, message } from "antd";
import { publish } from 'pubsub-js';
import { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';

import { Link } from "react-router-dom";
import { getUpdateGroupIntroduction, getUpdateGroupName } from '../../../../assets/js/api';
import { imgUrlDev, RTrim } from '../../../../assets/js/tools';
import { showGroupInfo } from '../../../../event-type';
import { changeCurrentRoomInfo } from '../../../../store/actions'

import {
    group_info_detail,
    group_info_tip,
    group_info_id,
    group_info_name,
    group_info_intro,
    group_info_member,
    group_info_member_title,
    group_info_member_content,
    group_info_member_num,
    user_avator_wrapper,
    user_avator_creator,
    user_avator_admin,
    user_avator_break,
    edit_icon,
    edit_input,
} from './index.module.css'

function GroupHoom(props) {

    const { groupInfo, identity, changeCurrentRoomInfo } = props;
    const groupNameInput = useRef(null);
    const groupIntroInput = useRef(null);

    const [editRowName, setEditRowName] = useState('');

    useEffect(() => {
        switch(editRowName) {
            case 'group_name':
                groupNameInput.current.focus();
                groupNameInput.current.select();
                break;
            case 'group_intro':
                groupIntroInput.current.focus();
                groupIntroInput.current.select();
                break;
            default:
                break;
        }
    }, [editRowName]);

    function formatDate(date) {
        // 返回年月日
        const dateTime = new Date(date);
        return `${dateTime.getFullYear()}/${dateTime.getMonth() + 1}/${dateTime.getDate()}`
    }
    function creator() {
        // 群主头像显示
        const creatorInfo = groupInfo.admin.find(val => val.user_id === groupInfo.creator_id);
        if (!creatorInfo) {
            message.open({type: 'error',content: '网络错误'});
            return;
        }
        
        return (
            <Link to={{pathname: `/info/${creatorInfo.user_id}`}} target="_blank">
                <Avatar 
                    className={`${user_avator_wrapper} ${user_avator_creator}`} 
                    src={imgUrlDev(creatorInfo.user_avator)} 
                    size={44}
                />
            </Link>
        )
    }
    function memberlist() {
        // 管理员头像列表显示
        const creatorIndex = groupInfo.admin.findIndex(val => val.user_id === groupInfo.creator_id);
        const admins = [...groupInfo.admin];
        admins.splice(creatorIndex, 1);
        return (
            admins.length > 0 ? 
                <>
                    <span className={user_avator_break}></span>
                    {
                        admins.map(item => {
                            return (
                                <Link to={{pathname: `/info/${item.user_id}`}} target="_blank" key={item.user_id}>
                                    <Avatar 
                                        className={`${user_avator_wrapper} ${user_avator_admin}`} 
                                        src={imgUrlDev(item.user_avator)} 
                                        size={44}
                                    />
                                </Link>
                            )
                        })
                    }
                </> : 
                ''
        )
    }

    function editInputCss(currentEditRownName, more = {
        height: '20px',
        width: 'auto'
    }) {
        // 显示的input样式,有关点击修改后的和为点击修改的样式
        return {
            ...more,
            visibility:  editRowName === currentEditRownName ? 'visible' : 'hidden',
            height:  editRowName === currentEditRownName ? more.height ?? '20px' : '0',
            width:  editRowName === currentEditRownName ? more.width ?? 'auto' : '0'
        }
    }
    function commitChange(e, varName) {
        // 'group_name', groupInfo.group_name
        // 'group_intro', groupInfo.group_intro
        const value = e.target.value;
        if (value === RTrim(groupInfo[varName])) {
            setEditRowName('');
            return;
        }

        let commitPromise = null;
        if (varName === 'group_name') {
            commitPromise = getUpdateGroupName({group_id: groupInfo.group_id, group_name: value})
        } else if (varName === 'group_intro') {
            commitPromise = getUpdateGroupIntroduction({group_id: groupInfo.group_id, group_intro: value})
        }
        commitPromise.then(res => {
            const {code, message: content, data} = res.data;
            if (code !== 1) {
                message.open({type: 'error', content});
                return;
            }
            changeCurrentRoomInfo(data);
            publish(showGroupInfo, data);       // 重新发布一次打开信息框,更新信息
        })
        .catch(err => {
            console.log(err);
            e.target.value = groupInfo[varName];
        });
        setEditRowName('');
    }
    
    return (
        <div className={group_info_detail}>
            {
                // 用户不在群组内则不显示群号码和群名称
                identity > 0 ? 
                    <>
                        <span className={group_info_id}>
                            <span className={group_info_tip}>群号码</span> {groupInfo.group_id}
                        </span>
                        <span className={group_info_name}>
                            <span className={group_info_tip}>群名称</span>
                            {
                                editRowName !== 'group_name' ?
                                    <>
                                        {groupInfo.group_name}
                                        {
                                            identity > 1 ? <EditOutlined className={edit_icon} onClick={() => setEditRowName('group_name')} /> : ''
                                        }
                                    </> : ''
                            }
                            <input 
                                style={editInputCss('group_name')}
                                className={edit_input}
                                type="text" 
                                ref={groupNameInput}
                                defaultValue={groupInfo.group_name} 
                                onBlur={e => commitChange(e, 'group_name')} 
                            />
                        </span>
                    </> :
                    ''
            }
            <span className={group_info_intro}>
                <span className={group_info_tip}>群介绍</span>
                {
                    editRowName !== 'group_intro' ?
                        <>
                            本群创建于{formatDate(groupInfo.create_time)}{groupInfo.group_intro ? groupInfo.group_intro : '群主很懒,什么都没有留下'}： 
                            {
                                identity > 1 ? <EditOutlined className={edit_icon} onClick={() =>  setEditRowName('group_intro')} /> : ''
                            }
                        </> : ''
                }
                <textarea 
                    style={editInputCss('group_intro', {
                        resize: 'none',
                        height: '100px',
                        width: '100%'
                    })}
                    className={edit_input}
                    ref={groupIntroInput}
                    defaultValue={groupInfo.group_intro} 
                    onBlur={e => commitChange(e, 'group_intro')} 
                />
            </span>
            <div className={group_info_member}>
                <span className={`${group_info_member_title} ${group_info_tip}`}>群主/管理员</span>
                <div className={group_info_member_content}>
                    { creator() }
                    { memberlist() }
                </div>
            </div>
            <span className={group_info_member_num}>
                <span className={group_info_tip}>成员数目</span>
                {groupInfo.people_num}
            </span>
        </div>
    )
}


function mapStateToProps(state) {
    return {

    }
}
export default connect(
    mapStateToProps,
    {
        changeCurrentRoomInfo
    }
)(GroupHoom);


